package com.itheima.tlias84.aspect;

import com.alibaba.fastjson2.JSONObject;
import com.itheima.tlias84.Po.InsertLogParam;
import com.itheima.tlias84.Service.LogService;
import com.itheima.tlias84.Util.JwtUtil;
import com.itheima.tlias84.mapper.LogMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Aspect 标识切面类
 */
@Slf4j
@Aspect
@Component
public class LogAspect {
    @Resource
    HttpServletRequest request;
    @Resource
    LogService logService;
    @Resource
    LogMapper logMapper;

    @Around("@annotation(com.itheima.tlias84.annotation.Log)")
    public Object insertLog(ProceedingJoinPoint joinPoint)  {
        //执行父类方法
        try {
            Object proceed = joinPoint.proceed();
            //设置开始计时时间
            long start = System.currentTimeMillis();

            log.info("操作{}方法插入日志",joinPoint.getSignature().getName());
            //获取token
            JSONObject token = JwtUtil.verifyToken(request.getHeader("token"));
            //获取用户名
            String username = token.getString("username");

            InsertLogParam build = InsertLogParam.builder()
                    .operateEmpName(username)
                    .operateTime(LocalDateTime.now())
                    .className(joinPoint.getTarget().toString())
                    .methodName(joinPoint.getSignature().getName())
                    .methodParams(JSONObject.toJSONString(joinPoint.getArgs()))
                    .returnValue(JSONObject.toJSONString(proceed))
                    .costTime(System.currentTimeMillis() - start)
                    .build();
            logMapper.insertLog(build);

            return proceed;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }





    }
}
